package main.chapter6

import java.io.ByteArrayOutputStream
import java.net.URL

interface Response {
    fun getResponse(result: ByteArray)
}

fun downloadService(url: String, response: Response) {
    val imgUrl = URL(url);
    //打开连接
    val urlConnection = imgUrl.openConnection()
    val inputStream = urlConnection.getInputStream()
    //将inputStream解析为Byte[]
    val output = ByteArrayOutputStream()
    val buffer = ByteArray(4096)
    while (true) {
        val result = inputStream.read(buffer)
        if (result == -1) {
            break
        } else {
            output.write(buffer, 0, result)
        }
    }
    response.getResponse(output.toByteArray())
}

fun downloadService(url: String): ByteArray {
    val imgUrl = URL(url);
    //打开连接
    val urlConnection = imgUrl.openConnection()
    val inputStream = urlConnection.getInputStream()
    //将inputStream解析为Byte[]
    val output = ByteArrayOutputStream()
    val buffer = ByteArray(4096)
    while (true) {
        val result = inputStream.read(buffer)
        if (result == -1) {
            break
        } else {
            output.write(buffer, 0, result)
        }
    }
    return output.toByteArray()
}
